package com.iot08.common.config.mongodb;

import com.iot08.common.config.mongodb.converter.MongoDateReadingHandle;
import com.iot08.common.config.mongodb.converter.MongoDateWritingHandle;
import com.mongodb.client.MongoClients;
import lombok.Data;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import java.util.ArrayList;
import java.util.List;


/**
 * @version 1.0
 * @Description: MongoDB配置类
 * @time: 2020/8/22 9:57
 * @author: Rock
 */
@Data
public abstract class MongoConfig {

    protected String uri;

    protected String databaseName;

    public MongoDatabaseFactory mongoDbFactory() {
        return new SimpleMongoClientDatabaseFactory(MongoClients.create(uri), databaseName);
    }

    public abstract MongoTemplate getMongoTemplate(MongoMappingContext context, BeanFactory beanFactory);

    /**
     * 自定义转换器注册
     *
     * @time: 2020/9/27 15:08
     * @author: Rock
     * @version 1.0
     */
    @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(new MongoDateWritingHandle());
        converterList.add(new MongoDateReadingHandle());
        return new MongoCustomConversions(converterList);
    }

}
